import time
from vnpy_ctastrategy.template import(
    CtaTemplate
)
from vnpy.trader.object import(
    BarData,
    TickData,
    TradeData,
    OrderData
)

from base import StopOrder
from vnpy.trader.constant import Status

from vnpy.trader.utility import(
    BarData,
    
)

# from vnpy.trader.utility import(
#     BarGenerator,
#     ArrayManager
# )
from typing import Any

class LiangCha(CtaTemplate):
    """"""

    author="LiangCha"

    status=""
    oldPrice=0
    nowPrice=0

    myprice=0
    stopSunPrice=0
    stopYingPrice=0

    volCha=0
    volChaNow=0

    parameters=[  
        "volCha"
    ]

    variables=[
        "volChaNow",
        "myprice",
        "stopSunPrice",
        "stopYingPrice"
        
    ]

    def __init__(self, cta_engine: Any, strategy_name: str, vt_symbol: str, setting: dict) -> None:
        super().__init__(cta_engine, strategy_name, vt_symbol, setting)
        self.orderid=""
        self.stoporderid=""
        self.vt_stoporderid=""
        self.limitorderid=""
        self.status="等待中"
        # self.msg=f",pos={self.pos},orderid={self.orderid},myprice={self.myprice}，stopSunPrice={self.stopSunPrice},stopYingPrice={self.stopYingPrice},volCha={self.volChaNow}"
        # self.bg = BarGenerator(self.on_bar)
        # self.am = ArrayManager()

    def on_init(self) -> None:
        self.write_log("市价LiangCha 策略初始化")
        # self.load_bar(10)

    def on_start(self) -> None:
        self.pos=0
        self.write_log("市价LiangCha 策略启动")
    
    def on_stop(self) -> None:
        # self.startTrade=0
        self.write_log("市价LiangCha 策略停止")

    def on_trade(self, trade: TradeData) -> None:
        self.myLog(action="on_trade",msg=f"{trade}")
        return super().on_trade(trade)

    def on_stop_order(self, stop_order: StopOrder) -> None:
        self.myLog(action="on_stop_order",msg=f"{stop_order}")
        if self.stoporderid.find(stop_order.stop_orderid)!=-1:
            if stop_order.status.value==StopOrder.status.TRIGGERED.value:
                self.vt_stoporderid=stop_order.vt_orderids[0]
                self.myLog("止损中1")
        return super().on_stop_order(stop_order)

    def on_order(self, order: OrderData) -> None:
        self.myLog(action="on_order",msg=f"{order}")
        if self.orderid.find(order.orderid)!=-1:
            if order.status==Status.REJECTED:
                self.myLog("已拒单")
                self.status="等待中"
            elif order.status==Status.CANCELLED:
                self.myLog("已撤单")
                self.status="等待中"
            elif order.status==Status.ALLTRADED:
                self.myLog("已开仓")
                self.status="开盈中"
                self.limitorderid=self.cover(self.stopYingPrice, 1)[0]
                # TODO 止盈单挂单失败 需要特殊处理
        elif self.limitorderid.find(order.orderid)!=-1:
            if order.status==Status.NOTTRADED:
                self.status="波动中"
            elif order.status==Status.ALLTRADED:
                self.myLog("已止盈")
                self.status="等待中"
            elif order.status==Status.CANCELLED:
                self.myLog("已撤盈")
                self.status="开损中"
                self.stoporderid=self.cover(self.stopSunPrice, 1,True)[0]
        elif self.vt_stoporderid.find(order.orderid)!=-1:
            if order.status==Status.NOTTRADED or order.status==Status.SUBMITTING:
                self.myLog("止损中2")
            elif order.status==Status.ALLTRADED:
                self.myLog("已止损")
                self.status="等待中"
        return super().on_order(order)

    def on_tick(self, tick: TickData) -> None:
        self.tick=tick
        self.nowPrice=tick.last_price
        self.checkToMove(tick)
        self.oldPrice=tick.last_price

        '''
        status 等待中 检查开仓条件 开仓 status->开仓中
        status 开仓中 
            检查放弃开仓条件 cancel订单 ->撤单中
            等待onOrder开仓成功 ->已开仓
            等待onOrder开仓失败 ->等待中
        status 撤单中 等待onorder撤单成功 ->等待中
        status 已开仓 下止盈单 ->开盈中
        status 开盈中 
            等待onOrder返回未成交 ->波动中
            -- 等待onOrder返回拒单 ->波动中
        status 波动中 
            onOrder改变止盈单状态为 全部成交 ->等待中
            达到止损条件 撤回止盈单 ->撤盈中
        status 撤盈中 等待OnOrder撤回止盈单成功 ->已撤盈
        status 已撤盈 开止损-> 开损中
        status 开损中 等待OnStopOrder开止损单成功 ->止损中
        status 开损中 止损中 等待OnStopOrder止损成功 ->等待中
        '''
        if self.trading:
            if self.status=="等待中":
                if self.orderid:
                    self.orderid=""
                    self.limitorderid=""
                    self.stoporderid=""
                self.volChaNow=tick.bid_volume_1-tick.ask_volume_1
                if self.volChaNow<=self.volCha:
                    self.status="开仓中"
                    self.myprice=tick.ask_price_1
                    self.myLog("开仓中")
                    self.orderid=self.short(self.myprice, 1)[0]
                    self.stopSunPrice=self.myprice+1
                    self.stopYingPrice=self.myprice-1
                else:
                    self.myLog("等待中",msg=f"volChaNow{self.volChaNow}<=volCha{self.volCha}")
            elif self.status=="开仓中":
                if self.myprice!=tick.ask_price_1:
                    self.status="撤单中"
                    self.myLog("撤单中")
                    self.cancel_order(self.orderid)
                    # TODO 极端情况 发送撤单的时候 已经成交 需要特殊处理
                else:
                    self.myLog("开仓中")
            elif self.status=="撤单中":
                self.myLog("撤单中")
            elif self.status=="波动中":
                self.myLog("波动中")
                if tick.bid_price_1>=self.myprice:
                    self.status="撤盈中"
                    self.myLog("撤盈中")
                    self.cancel_order(self.limitorderid)
            else:
                self.myLog(self.status)

        self.put_event

    def myLog(self,action,msg="") ->None:
        tick=self.tick
        if self.status=="波动中" or self.status=="开仓中":
                if self.oldPrice==self.nowPrice:
                    return
        t=time.strftime('%H:%M:%S',time.localtime(time.time()))
        if msg:
            print(f"{t} {action},{msg}")
        else:
            print(f"{t} {action},pos={self.pos},status={self.status},波动={self.myprice-tick.last_price},myprice={self.myprice}，lastPrice={tick.last_price},askPrice={tick.ask_price_1},bidPrice={tick.bid_price_1},orderid={self.orderid},limitorderid={self.limitorderid},stoporderid={self.stoporderid},vt_stoporderid={self.vt_stoporderid}")